#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <string>
#include <vector>
#include <cstdio> 
#include <cerrno>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/socket.h>
using namespace std;
#define MODE 0666
#define Path "./fifo"
class Fifo
{
private:
    string _path; // 文件路径+文件名
public:
    Fifo(const string& path = Path):
    _path(path)
    {
        int n = mkfifo(_path.c_str(), MODE);
        if(n == -1){
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
            exit(1);
        }else{
            cout<<"mkfifo success"<<endl;
        }
    }
    ~Fifo(){
        // 析构的时候将文件删掉.
        int n = unlink(_path.c_str()); // 用于删除文件,也可以用于删除链接文件.
        if(n==0){
            cout<<"remove fifo success!"<<endl;
        }else{
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
        }
    }
};

class Sync
{
public:
    Sync():wfd(-1),
    rfd(-1){}
    void OpenReadOrDie(){
        rfd = open(Path,O_RDONLY);
        if(rfd == -1){
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
        }
    }
    void OpenWriteOrDie(){
        wfd = open(Path,O_WRONLY);
        if(wfd == -1){
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
        }
    }
    
    bool Wait(){
        bool ret = true;
        uint32_t c =0;
        ssize_t n = read(rfd,&c,sizeof(uint32_t));
        if(n==sizeof(uint32_t)){
            cout<<"server wakeup!"<<endl;
        }else if(n==0){
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
            return false;
        }else{
            return false;
        }
        return ret;
    }
    void Wakeup(){
        uint32_t c =0;
        ssize_t n = write(wfd,&c,sizeof(uint32_t));
        if(n==sizeof(uint32_t)){
            cout<<"write success!"<<endl;   
        }else{
            cout<<"erron:"<<errno<<"  errorString:"<<strerror(errno)<<endl;
        }
    }
    
    ~Sync(){}
private:
    int rfd;
    int wfd;
};
#endif